package com.hzit.controller.admin;

import com.cwy.hzit.entity.LoginUser;
import com.hzit.entity.User;
import com.hzit.service.TokenService;
import com.hzit.service.UserService;
import com.cwy.hzit.utils.JwtUtil;
import com.cwy.hzit.utils.R;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Api(tags = "用户登录、注册接口")
public class AdminLoginController {
	@Autowired
	private UserService userService;
	@Autowired
	private TokenService tokenService;

	@PostMapping("/login")
	@ApiOperation("用户登录")
	public R login(
			@ApiParam(value = "登录用户对象", required = true)
			@RequestBody User user) {
		LoginUser loginUser = userService.findById(user.getUsername(), user.getPassword());
		if (loginUser == null) {
			return R.error().message("用户名或密码错误");
		}
		Map<String, Object> map = tokenService.createToken(loginUser);
		return R.ok().data(map);
	}

	@GetMapping("/info")
	@ApiOperation("获取用户信息")
	public R info(@RequestParam("token") String token) {
		try {
			Claims claims = JwtUtil.parseToken(token);
			String username = (String) claims.get("username");

			Map<String, Object> map = new HashMap<>();
			map.put("name", username);
			map.put("avatar", "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");

			return R.ok().data(map);
		} catch (Exception e) {
			return R.error().message("无效的 token");
		}
	}
	@PostMapping("/signIn")
	@ApiOperation("用户注册")
	public R userSignIn(@RequestBody User user) {
		boolean result = userService.saveUserMsg(user);
		return result ? R.ok().code(200).message("注册成功") : R.error().message("注册失败");
	}
}